import base64
import pickle
import re

from django.contrib.auth.backends import ModelBackend
from django_redis import get_redis_connection

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'username':user.username,
        "user_id":user.id
    }


# 重写多用户注册
class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:

            if re.match(r"1[3-9]\d{9}",username):
                # 如果是手机号,根据手机号查询用户
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None

        if user is not None and user.check_password(password):
            return user

def merge_cart_cookie_to_redis(request, user, response):
    """
    合并请求用户的购物车数据，将未登录保存在cookie里的保存到redis中
    遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    :param request: 用户的请求对象
    :param user: 当前登录的用户
    :param response: 响应对象，用于清楚购物车cookie
    :return:
    """
    cart_cookie = request.COOKIES.get("cart_cookie", None)

    # 解密
    if cart_cookie:
        cart = pickle.loads(base64.b64decode(cart_cookie))
    else:
        return response
    # 判断是否为空
    if not cart:
        return response
    # 拆分数据
    # 获取sku_id,count
    cart_dict = {}

    sku_selected = []
    sku_selected_none = []
    for skuids, data in cart.items():
        # 获取selected 放入集合 一个集合放true ，另一个放flase
        cart_dict[skuids] = data["count"]
        if data["selected"]:
            sku_selected.append(skuids)
        else:
            sku_selected_none.append(skuids)

    # 写入redis
    coon = get_redis_connection("cart")
    coon.hmset("cart_%s" % user.id, cart_dict)
    # 3.写入set
    if sku_selected:
        coon.sadd("cart_selected_%s" % user.id, *sku_selected)
    if sku_selected_none:
        coon.sadd("cart_selected_none%s" % user.id, sku_selected_none)
    #  删除cookie
    response.delete_cookie("cart_cookie")
    return response